import { initZwlog } from '@/utils/buriedPoint.js';
import { useAuthStore } from '@/stores';
const { setUserInfo } = useAuthStore();
import { post } from '@/api/http';

// import { isApp, isWeChart, isAlipay } from './userAgent';

// const ak = '15575b2d5e104a04bdb499801e9e245a';

const test = process.env.NODE_ENV != 'production';

const testTicket = 'debug_tk_e4a0dc3fcc8d464ba336b9bcb1ba2072';

export const handleLogin = async () => {
	if (testTicket && test) return getTokenByTicket(testTicket);

	// 获取应用ticketId
	const { ticketId, result } = await ZWJSBridge.ssoTicket({});

	if (!result) return console.error('当前容器环境不支持“浙里办”统一单点登录！');

	getTokenByTicket(ticketId);
};

/**
 * 根据票据获取 token 和 用户信息
 * @param {string} ticket 票据
 * @returns
 */
export const getTokenByTicket = (ticket) => {
	if (!ticket) return console.log('传入票据为空！');

	const params = {
		clientId: 'SQ2eMNHmoxxlvjZxI7VBdHNsFIKfPGNB',
		code: ticket,
	};
	console.log('票据：');
	console.log(params.code);

	const baseUrl = 'https://szsb.hzxh.gov.cn:8080/gatewayWx';
	// const baseUrl = 'http://192.168.0.123:8888';
	// const baseUrl = 'http://localhost:8080/api';
	post(baseUrl + '/front-user/zlbApi/auth/login', params, '登录').then(
		({ userInfo, token_type, access_token }) => {
			console.log('userInfo');

			console.log(userInfo);

			// 保存token
			sessionStorage.setItem('token', (token_type || '') + (access_token || ''));

			// 全局存入用户信息
			setUserInfo(userInfo);

			// 用户信息埋点
			const { zlbUserId, contactName } = userInfo;
			initZwlog(zlbUserId, contactName);
		}
	);
	// .finally(() => this.$router.push('/Home'));
};
